//
// Created by 33145 on 2023/2/6.
//
#include "sylar/http/http_server.h"
#include "sylar/log.h"

static sylar::Logger::ptr g_logger = SYLAR_LOG_ROOT();

#define XX(...) #__VA_ARGS__

std::map<std::string, std::string> g_username_passwd;

void user_init() {

}

// sylar::IOManager::ptr worker;
void run() {
  g_logger->setLevel(sylar::LogLevel::INFO);
  //sylar::http::HttpServer::ptr server(new sylar::http::HttpServer(true, worker.get(), sylar::IOManager::GetThis()));
  sylar::http::HttpServer::ptr server(new sylar::http::HttpServer(true));
  sylar::Address::ptr addr = sylar::Address::LookupAnyIPAddress("0.0.0.0:8020");
  while(!server->bind(addr)) {
    sleep(2);
  }
  auto sd = server->getServletDispatch();

  sd->addServlet("/t", [](sylar::http::HttpRequest::ptr req,
                           sylar::http::HttpResponse::ptr rsp,
                           sylar::http::HttpSession::ptr session) ->int32_t {
    // std::cout << req->toString() << " hello world " << std::endl;
    rsp->setHeader("Content-Type", "text/html;charset=utf-8");
    std::ifstream infile;
    std::stringstream buffer;
    infile.open("/home/orange/workspace/sylar/chat/html/chat_room.html");
    buffer << infile.rdbuf();
    rsp->setBody(buffer.str());
    return 0;
  });
  sd->addServlet("/", [](sylar::http::HttpRequest::ptr req,
                         sylar::http::HttpResponse::ptr rsp,
                         sylar::http::HttpSession::ptr session) ->int32_t {
    std::ifstream ifs("./html/index.html");
    if(!ifs) {
      rsp->setBody("invalid file");
      rsp->setStatus(sylar::http::HttpStatus::NOT_FOUND);
      return 0;
    }

    std::stringstream ss;
    std::string line;
    while(std::getline(ifs, line)) {
      //SYLAR_LOG_INFO(g_logger) << line;
      ss << line << std::endl;
    }

    rsp->setBody(ss.str());
    rsp->setHeader("content-type", "text/html;charset=utf-8");
    return 0;
  });

  sd->addServlet("/post", [](sylar::http::HttpRequest::ptr req,
                             sylar::http::HttpResponse::ptr rsp,
                             sylar::http::HttpSession::ptr session) ->int32_t {

    return 0;
  });

  server->start();
}

int main(int argc, char** argv) {
  sylar::IOManager iom(8);
  // worker.reset(new sylar::IOManager(3, false, "worker"));
  iom.schedule(run);
  return 0;
}